package com.zensation.ticklemepanda;

import java.util.List;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.zensation.ticklemepanda.definition.GlobalDefine;
import com.zensation.ticklemepanda.util.TickleMePandaSharedPreference;
import com.zensation.ticklemepanda.util.SoundManager;

import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

@SuppressWarnings("deprecation")
public class TickleMePandaActivity extends Activity implements SensorListener {

	// ======================Class,Variable define =======================
	private MainGameView gameView;
	private LinearLayout linearLayout;
	private TickleMePandaSharedPreference funnyAnimalGameSharedPreference;

	private AdView layoutAds;
	// For shake motion detection.
	private SensorManager sensorMgr;
	private long lastUpdate = -1;
	private float x, y, z;
	private float last_x, last_y, last_z;
	private static final int SHAKE_THRESHOLD = 1500;

	private static String shareMsgSubject;
	private static String shareMsgContent;
	private DisplayMetrics metrics;
	private int densityDevice;
	/*
	 * manage activity running
	 */
	public ActivityManager actManager = null;
	private List<RunningAppProcessInfo> runningProcInfo;
	/*
	 * handler to control the dialog win game
	 */
	public final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case GlobalDefine.DIALOG_WIN_GAME:
			// Level Up
			{
				showDialog(GlobalDefine.DIALOG_WIN_GAME);
				break;
			}
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

		setContentView(R.layout.page_main_screen);
		initializeView();

		// start motion detection
		sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
		boolean accelSupported = sensorMgr.registerListener(this,
				SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_GAME);

		if (!accelSupported) {
			// on accelerometer on this device
			sensorMgr.unregisterListener(this, SensorManager.SENSOR_ACCELEROMETER);
		}
		// share subject and content text
		shareMsgSubject = getResources().getString(R.string.shared_msg_subject);
		shareMsgContent = getResources().getString(R.string.shared_msg_content);

	}

	// initialize class,layout and surface view
	private void initializeView() {
		// class define
		gameView = new MainGameView(TickleMePandaActivity.this);
		funnyAnimalGameSharedPreference = TickleMePandaSharedPreference.getInstance(this);
		// start game with the progress bar is empty
		funnyAnimalGameSharedPreference.putScoreValue(0);
		// calculate density of device
		metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		densityDevice = metrics.densityDpi;
		funnyAnimalGameSharedPreference.putDensityValue(densityDevice);

		linearLayout = (LinearLayout) findViewById(R.id.gameView);
		linearLayout.addView(gameView);

		refreshAdsMob();
		// // Look up the AdView as a resource and load a request.
		layoutAds = (AdView) this.findViewById(R.id.main_adView);

		// Initiate a generic request to load it with an ad
		AdRequest adRequest = new AdRequest();
		layoutAds.loadAd(adRequest);
		layoutAds.bringToFront();
	}

	// refresh adsmobs after 30 seconds
	private void refreshAdsMob() {
		new CountDownTimer(12000, 10000) {

			@Override
			public void onTick(long millisUntilFinished) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFinish() {
				// Initiate a generic request to load it with an ad
				AdRequest adRequest = new AdRequest();
				layoutAds.refreshDrawableState();
				layoutAds.loadAd(adRequest);
				layoutAds.invalidate();
				layoutAds.bringToFront();
				refreshAdsMob();
			}
		}.start();
	}

	@Override
	public void onAccuracyChanged(int sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(int sensor, float[] values) {
		if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
			long curTime = System.currentTimeMillis();
			// only allow one update every 100ms.
			if ((curTime - lastUpdate) > 100) {
				long diffTime = (curTime - lastUpdate);
				lastUpdate = curTime;

				x = values[SensorManager.DATA_X];
				y = values[SensorManager.DATA_Y];
				z = values[SensorManager.DATA_Z];

				float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
				if (speed > SHAKE_THRESHOLD) {
					// yes, this is a shake action! Do something about it!
					gameView.setShakePhone(true);
				} else
					gameView.setShakePhone(false);

				last_x = x;
				last_y = y;
				last_z = z;
			}
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	protected void onResume() {
		super.onResume();
		if (sensorMgr == null)
			sensorMgr.registerListener(this, SensorManager.SENSOR_ACCELEROMETER,
					SensorManager.SENSOR_DELAY_GAME);
		if (funnyAnimalGameSharedPreference.getScoreValue() >= GlobalDefine.WIN_SCORE) {
			sendMS(GlobalDefine.DIALOG_WIN_GAME);
		}
	}

	protected void onDestroy() {
		super.onDestroy();
		freeMemory();
	}

	/*
	 * free memory after sign out app
	 */
	private void freeMemory() {
		actManager = (ActivityManager) this.getSystemService(Activity.ACTIVITY_SERVICE);
		runningProcInfo = ((ActivityManager) actManager).getRunningAppProcesses();

		for (int i = 0; i < runningProcInfo.size(); i++) {
			String str = runningProcInfo.get(i).processName.toString();
			PackageInfo pi;
			try {
				pi = getPackageManager().getPackageInfo(str, 0);
				String packageName = pi.applicationInfo.packageName;
				if (packageName.equals(this.getPackageName()))
					actManager.restartPackage(packageName);
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// gameLoopThread.setRunning(false);
			gameView.getThread().setPause(true);
			DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
					// Yes button clicked
					{
						SoundManager.getCrySound(TickleMePandaActivity.this).pause();
						SoundManager.getGiggleSound(TickleMePandaActivity.this).pause();
						SoundManager.getSleepSound(TickleMePandaActivity.this).pause();
						finish();
						System.gc();
						break;
					}
					case DialogInterface.BUTTON_NEGATIVE:
						// No button clicked
						gameView.getThread().setPause(false);
						break;
					}
				}
			};
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(R.string.exit_text)
					.setPositiveButton(R.string.positive_text, dialogClickListener)
					.setNegativeButton(R.string.negative_text, dialogClickListener);
			builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					// TODO Auto-generated method stub
					gameView.getThread().setPause(false);
				}
			});
			builder.show();
			return true;

		}
		if (keyCode == KeyEvent.KEYCODE_CALL) {
			this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * create dialog win game
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		SoundManager.stopAll(TickleMePandaActivity.this);
		switch (id) {
		case GlobalDefine.DIALOG_WIN_GAME:
			DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						// Share button clicked
						shareContent(shareMsgSubject, shareMsgContent);
						break;
					case DialogInterface.BUTTON_NEUTRAL:
						// Play again button clicked
						funnyAnimalGameSharedPreference.putScoreValue(0);
						gameView.resetGame();
						gameView.getThread().setPause(false);

						break;
					case DialogInterface.BUTTON_NEGATIVE:
						// Exit button clicked
						funnyAnimalGameSharedPreference.putScoreValue(0);
						finish();
						break;
					}
				}
			};
			AlertDialog.Builder builder = new AlertDialog.Builder(TickleMePandaActivity.this);
			builder.setMessage(R.string.text_win_game).setIcon(R.drawable.ic_launcher)
					.setTitle(getString(R.string.app_name)).setCancelable(false)
					.setPositiveButton(R.string.text_btn_share, dialogClickListener)
					.setNeutralButton(R.string.text_btn_play_again, dialogClickListener)
					.setNegativeButton(R.string.text_btn_exit, dialogClickListener);
			return builder.create();
		}
		return null;
	}

	public void sendMS(int wh) {
		Message ms = new Message();
		ms.what = wh;
		handler.sendMessage(ms);
	}

	/*
	 * share content when win game
	 */
	private void shareContent(String subject, String content) {
		Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		// set the type
		shareIntent.setType("text/plain");
		// add a subject
		shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
		// build the body of the message to be shared
		String shareMessage = content;
		// add the messagelăm
		shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareMessage);
		// start the chooser for sharing
		startActivity(Intent.createChooser(shareIntent, "Share"));
	}
}
